// 请求基础路径
import { config } from "./config";
import { db } from "./db";
import { auth } from "./auth";
import { RequestData, ResponseData, RequestHeader } from "../api/types";

let isRefreshing = false; // 添加一个标记，表示是否正在刷新 token
let refreshPromise: Promise<boolean> | null = null; // 用于保存刷新 token 的 Promise
// 请求封装
const request = async (options: RequestData<any> = {}): Promise<ResponseData<any>> => {
  if (db.isTokenExpire()) {
    // token过期，需要刷新token
    if (!isRefreshing) {
      isRefreshing = true;
      // 刷新token
      if (!refreshPromise) {
        //重新创建一个新的 Promise
        refreshPromise = new Promise<boolean>((resolve, reject) => {
          auth.refreshToken()
            .then(() => resolve(true))
            .catch(err => {
              //清理登录信息
              wx.clearStorage();
              reject(err);
            });
        });
      }
      await refreshPromise;
      isRefreshing = false; // 标记为已刷新 token
    } else {
      // 正在刷新 token，等待刷新完成
      await refreshPromise!;
    }
  }
  // 发送请求
  try {
    // 请求header
    const header: RequestHeader = {
      "content-type": "application/json",
      "Authorization": db.getBearerToken()
    }
    const response = await sendRequest(options, header);
    return response;
  } catch (error) {
    return Promise.reject(error);
  }
}
const sendRequest = (options: RequestData<any>, header: RequestHeader): Promise<ResponseData<any>> => {
  return new Promise((resolve, reject) => {
    wx.request({
      url: config.baseUrl + options.url,
      method: options.method,
      data: options.data,
      header: header,
      success(response) {
        if (response.statusCode === 200) {
          resolve({
            code: response.statusCode,
            message: response.errMsg,
            data: response.data
          } as ResponseData<any>)
        } else if (response.statusCode === 401) {
          console.log("token过期....")
          //清理登录信息.
          wx.clearStorage();
          //重新登录.
          // auth.silentLogin().then(() => {
          //   resolve(sendRequest(options, header));
          // });
        } else {
          wx.showToast({
            title: response.errMsg,
            icon: "none",
            duration: 2000
          });
          resolve({
            code: response.statusCode,
            message: response.errMsg,
            data: response.data
          } as ResponseData<any>);
        }
      },
      fail(error) {
        reject(error);
      }
    })
  })
}

export { request, sendRequest };
